package cn.ly.jvm.loader;

import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.List;

public class MyClassLoader extends ClassLoader{
	
	private String classPath;
	
	public MyClassLoader(String classPath){
		this.classPath = classPath;
	}
	
	@Override
	protected Class<?> findClass(String name){
		String pathName = name.replaceAll("\\\\.", "\\\\");
		String filePath = classPath + pathName;
		byte[] bytes = null;
		try {
			//FileInputStream fis = new FileInputStream("E:\\newtest\\workspace\\JavaTest\\bin\\cn\\ly\\jvm\\loader\\2\\TestLoader.class");
			FileInputStream fis = new FileInputStream("E:\\newtest\\workspace\\JavaTest\\bin\\cn\\ly\\jvm\\loader\\TestLoader.class");
			ByteArrayOutputStream bos = new ByteArrayOutputStream();
			bos = getOutput(fis,bos);
			bytes = bos.toByteArray();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		//name = name.substring(0,name.lastIndexOf(".")-2) + name.substring(name.lastIndexOf("."),name.length());
		return defineClass(name, bytes, 0, bytes.length);
	}
	
	public Class<?> loadClass2(String name){
		return findClass(name);
	}
	
	//获得输出流
	public ByteArrayOutputStream getOutput(FileInputStream fis,ByteArrayOutputStream bos) throws Exception{
		byte[] bytes = new byte[1024];
		int len = 0;
		while( (len=fis.read(bytes)) != -1){
			bos.write(bytes, 0, len);
		}
		return bos;
	}
	
	public static void main(String[] args) throws Exception {
		String path = "E:\\newtest\\workspace\\JavaTest\\bin\\";
		MyClassLoader myLoader = new MyClassLoader(path);
		System.out.println("parent=="+myLoader.getParent());
		System.out.println(myLoader.getClass().getClassLoader().getClass().getName());
		//System.out.println(TestLoader.class);
		//Class myTestLoader1 = Class.forName("cn.ly.jvm.loader.TestLoader");
		Class myTestLoader = myLoader.loadClass2("cn.ly.jvm.loader.TestLoader");
		//TestLoader testLoaderObj1 = (TestLoader)myTestLoader1.newInstance();
		//TestLoader testLoaderObj = (cn.ly.jvm.loader.TestLoader)myTestLoader.newInstance();

		//Class.forName("cn.ly.jvm.loader.TestLoader");
		//System.out.println(myTestLoader);
		System.out.println(myTestLoader.getClassLoader());
		//TestLoader.getMyLoader();
		myLoader = null;
		myTestLoader = null;
		/*List<Object> list = new ArrayList<Object>();
		for(int i = 0; ; i++){
			list.add(new Object());
			if(i%100000 == 0){
				System.gc();
				Thread.sleep(1000);
				System.out.println(i);
			}
		}*/
		

		
	}

}

